#include <workflow/WFFacilities.h>
#include <workflow/WFTaskFactory.h>
#include <workflow/HttpUtil.h>
#include <workflow/Workflow.h>
#include <workflow/WFHttpServer.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <vector>
#include <iostream>
#define print1

using std::cout;
using std::cerr;
using std::string;
using std::vector;

static WFFacilities::WaitGroup waitGroup(1);

void handler(int) {
    cout << "done!\n";
    waitGroup.done();
}

void process(WFHttpTask *serverTask) {
    /* process在被调用的时候，请求已经被server对象收好了 */
    protocol::HttpRequest *req = serverTask->get_req(); // 请求已经有了

#ifdef print1
    printf("request method = %s request path&query = %s request http version = %s\n",
           req->get_method(), req->get_request_uri(), req->get_http_version());
#endif

#ifdef print2
    protocol::HttpHeaderCursor reqCursor(req);
    string key, value;
    while(reqCursor.next(key, value)){
        printf("key = %s, value = %s\n", key.c_str(), value.c_str());
    }
#endif

    const void* body;
    size_t size;
    req->get_parsed_body(&body, &size);

    string respbody = string((char*)body);
    auto  resp = serverTask->get_resp();
    resp->add_header_pair("key1", "value1");
    resp->append_output_body(respbody);

#ifdef redirect
    resp->set_status_code("301");
    resp->set_reason_phrase("Moved Permanently");
    resp->add_header_pair("Location", "http://www.baidu.com");
#endif
}

int main() {
    signal(SIGINT, handler);

    /* 1.创建一个server对象 */
    WFHttpServer server(process);

    /**
     * 2.启动server，之后server会等待客户端接入
     * 当有客户端接入时，创建一个序列，执行任务，任务的基本工作是process
     */
    if (server.start(8889) == 0) {
        waitGroup.wait();
        server.stop();
    } else {
        perror("server start failed");
        return -1;
    }

    cout << "finished!\n";
    return 0;
}